package com.zone.lib.download.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.zone.lib.download.DownloadStatus;
import com.zone.lib.download.bean.DownloadInfo;
import com.zone.lib.download.bean.RequestInfo;
import com.zone.lib.download.config.InnerConstant;
import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.execute.DownloadExecutor;
import com.zone.lib.download.execute.DownloadTask;
import com.zone.lib.download.utils.AppStatusUpdateNotify;
import com.zone.lib.download.utils.LogUtils;

import org.apache.commons.lang3.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

public class DownloadService extends Service {

    public static final String TAG = DownloadService.class.getName();

    public static boolean canRequest = true;

    //关于线程池的一些配置
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = Math.max(3, CPU_COUNT/2);
    private static final int MAX_POOL_SIZE = CORE_POOL_SIZE * 2;
//    private static final int MAX_POOL_SIZE =  3;
    private static final long KEEP_ALIVE_TIME  = 1000000L;

    private DownloadExecutor mExecutor = new DownloadExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
            KEEP_ALIVE_TIME, TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>());

    //存储任务
    private HashMap<String, DownloadTask> mTasks = new HashMap<>();

    public DownloadService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (canRequest){
            LogUtils.i(TAG, "onStartCommand() -> 启动了service服务 intent=" + intent + "\t this=" + this);
            canRequest = false;

            if (null != intent && intent.hasExtra(InnerConstant.Inner.SERVICE_INTENT_EXTRA)){
                try {
                    ArrayList<RequestInfo> requesetes =
                            (ArrayList<RequestInfo>)intent.getSerializableExtra(InnerConstant.Inner.SERVICE_INTENT_EXTRA);
                    if (null != requesetes && requesetes.size()>0){
                        for (RequestInfo request : requesetes){
                            executeDownload(request);
                        }
                    }
                }catch (Exception e){
                    LogUtils.i(TAG, "onStartCommand()-> 接受数据,启动线程中发生异常");
                    e.printStackTrace();
                }
            }
            canRequest = true;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //Todo  除了简单的synchronized, 是否有更好的方式来进行加锁呢
    private synchronized void executeDownload(RequestInfo requestInfo){
        Log.d(TAG, "executeDownload start");
        DownloadInfo mDownloadInfo = requestInfo.getDownloadInfo();
        if (ObjectUtils.isEmpty(mDownloadInfo)){
            Log.d(TAG, "DownloadInfo is null, this task break out !");
            return;
        }
        //先看看在任务列表里，是否有这个任务
        DownloadTask task = mTasks.get(mDownloadInfo.getCode());
        Download download = requestInfo.getDownloadInfo().getDownload();
//        Download download = DownloadDaoUtilsStore.getInstance().getDownloadByCode(mDownloadInfo.getCode());

        if (null == task){ //之前没有类似任务
            Log.d(TAG, "task is null");
            if (null != download){
                Log.d(TAG, "download is not null");
                if (mDownloadInfo.getAction() == DownloadStatus.PREPARE_DOWNLOAD
                        && (download.getDownloadStatus()== DownloadStatus.PAUSE_DOWNLOAD
                        || download.getDownloadStatus()== DownloadStatus.FAIL_DOWNLOAD)){
                    //修正文件状态
                    download.setDownloadStatus(mDownloadInfo.getAction());
                    AppStatusUpdateNotify.appNotify(getApplicationContext(), mDownloadInfo, download);
                }else if (download.getDownloadStatus() == DownloadStatus.COMPLETE_DOWNLOAD){
                    Log.e(TAG, "this app " + download.getCode() +" is finish download ");
                    return;
//                    if (mDownloadInfo.getFile().exists()){
//                        if (mDownloadInfo.getAction() > 0){
//                            Intent intent = new Intent();
//                            intent.setAction(String.valueOf(mDownloadInfo.getAction()));
//                            intent.putExtra(DownloadConstant.EXTRA_INTENT_DOWNLOAD, download);
//                            sendBroadcast(intent);
//                        }
//                        return;
//                    } else {
////                        DownloadDaoUtilsStore.getInstance().deleteByCode(download.getCode());
////                        dbHolder.deleteFileInfo(mDownloadInfo.getUniqueId());
//                    }
                }
            }else {
                //创建下载记录
                Log.e(TAG, "download is null");
                return;
            }
            Log.d(TAG, "DownloadInfo "+ JSON.toJSONString(requestInfo.getDownloadInfo()));
            //创建一个下载任务
            if (mDownloadInfo.getAction() == DownloadStatus.WAIT_DOWNLOAD
                        || mDownloadInfo.getAction() == DownloadStatus.PREPARE_DOWNLOAD
                    || mDownloadInfo.getAction() == DownloadStatus.PAUSE_DOWNLOAD){
                task = new DownloadTask(this, mDownloadInfo);
                mTasks.put(mDownloadInfo.getCode(), task);
            }
        }else {
            // 什么情况下, 可能存在这种这种状态
            if (mDownloadInfo.getAction() == DownloadStatus.PAUSE_DOWNLOAD
                    && (task.getStatus() == DownloadStatus.LOADING_DOWNLOAD
                        || task.getStatus() == DownloadStatus.PREPARE_DOWNLOAD)){
                task.pause();
            }else if (mDownloadInfo.getAction() == DownloadStatus.PREPARE_DOWNLOAD
                    && (task.getStatus() == DownloadStatus.WAIT_DOWNLOAD
                        || task.getStatus() == DownloadStatus.PAUSE_DOWNLOAD)){
                task.restart();
                return;
            }else if (task.getStatus() == DownloadStatus.LOADING_DOWNLOAD
                    || task.getStatus() == DownloadStatus.DELETE_DOWNLOAD){
                if (!mDownloadInfo.getFile().exists()){
                    task.pause();
                    mTasks.remove(mDownloadInfo.getCode());
                    LogUtils.i(TAG, " 状态标示完成，但是文件不存在，重新执行下载文件  ");
                    executeDownload(requestInfo);
                    return;
                }
            }
        }

        if (null != task){
            Log.d(TAG, "task is not null! action = "+requestInfo.getDownloadInfo().getAction());
            if (mDownloadInfo.getAction() == DownloadStatus.PREPARE_DOWNLOAD){
                mExecutor.executeTask(task);
            }else {
                task.pause();
            }
        }
    }




}
